package com.tencent.texttoimage.hook;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.tencent.texttoimage.util.ToImage;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;

import static com.tencent.texttoimage.hook.Injector.TAG;

public class QQHook {

    private static final String KEY_IS_SEND_BUTTON = "KEY_IS_SEND_BUTTON";
    private static final String KEY_BASE_CHAT_PIE = "KEY_BASE_CHAT_PIE";

    private static final boolean enable_colorLevel = false;
    private static boolean sendByLongClick = true;
    private static boolean sendByClick = false;
    private static boolean isCleanEdit = true;

    private static Field patchedButtonField;
    private static Method onPrivateIMECommandMethod;


    public static void doHook(ClassLoader classLoader, Context context) throws IllegalAccessException {
        Log.d(TAG, "doHook method invoked!");

        /**
         * enable colorLevel qq日志级别
         * public static boolean isColorLevel() {
         * private static int UIN_REPORTLOG_LEVEL = 1;
         */
        if (enable_colorLevel) {
            XposedHelpers.findField(XposedHelpers.findClass("com.tencent.qphone.base.util.QLog", classLoader), "UIN_REPORTLOG_LEVEL")
                    .setInt(null, 2);
        }

        Class xEditTextExClass = XposedHelpers.findClass("com.tencent.widget.XEditTextEx", classLoader);
        final Class baseChatPieClass = XposedHelpers.findClass("com.tencent.mobileqq.activity.BaseChatPie", classLoader);
        final Class patchedButtonClass = XposedHelpers.findClass("com.tencent.widget.PatchedButton", classLoader);
        final Field xEditTextExField = XposedHelpers.findFirstFieldByExactType(baseChatPieClass, xEditTextExClass);

        //    public boolean onPrivateIMECommand(String str, Bundle bundle) {
        onPrivateIMECommandMethod = XposedHelpers.findMethodBestMatch(xEditTextExClass, "onPrivateIMECommand", String.class, Bundle.class);


        //    public void setOnClickListener(@Nullable OnClickListener l) {
        XposedHelpers.findAndHookMethod(View.class, "setOnClickListener", View.OnClickListener.class, new XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                if (patchedButtonClass.isInstance(param.thisObject)
                        && baseChatPieClass.isInstance(param.args[0])
                        && "发送".contentEquals(((Button) param.thisObject).getText())) {

                    if (patchedButtonField == null) {
                        for (Field field : baseChatPieClass.getDeclaredFields()) {
                            if (field.getType() == patchedButtonClass) {
                                field.setAccessible(true);
                                if (field.get(param.args[0]) == param.thisObject) {
                                    patchedButtonField = field;
                                    Log.d(TAG, "found patchedButtonField: " + patchedButtonField);
                                }
                            }
                        }
                    }
                    if (sendByLongClick) {// 这些东西只有在byLongClick的时候才要用到
                        XposedHelpers.setAdditionalInstanceField(param.thisObject, KEY_IS_SEND_BUTTON, true);
                        XposedHelpers.setAdditionalInstanceField(param.thisObject, KEY_BASE_CHAT_PIE, param.args[0]);
                    }
                }
            }
        });

        if (sendByLongClick) {
            //    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
            XposedHelpers.findAndHookMethod(View.class, "setOnLongClickListener", View.OnLongClickListener.class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    if (patchedButtonClass.isInstance(param.thisObject) && Boolean.TRUE.equals(XposedHelpers.getAdditionalInstanceField(param.thisObject, KEY_IS_SEND_BUTTON))) {
                        param.args[0] = new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                Object baseChatPie = XposedHelpers.getAdditionalInstanceField(v, KEY_BASE_CHAT_PIE);
                                if (baseChatPieClass.isInstance(baseChatPie)) {
                                    try {
                                        EditText editText = (EditText) xEditTextExField.get(baseChatPie);
                                        generateAndSend(editText);
                                    } catch (IllegalAccessException e) {
                                        Log.e(TAG, "errors on proxy OnLongClickListener", e);
                                    }
                                }
                                return true;
                            }
                        };
                    }
                }
            });
        }

        if (sendByClick) {
            XposedHelpers.findAndHookMethod(baseChatPieClass, "onClick", View.class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    View view = (View) param.args[0];
                    if (view != null && patchedButtonField != null && view == patchedButtonField.get(param.thisObject)) {
                        EditText editText = (EditText) xEditTextExField.get(param.thisObject);
                        generateAndSend(editText);
                        param.setResult(null);
                    }
                }
            });
        }


        /**
         * 假装成正在使用搜狗输入法
         */
        XposedHelpers.findAndHookMethod(Settings.Secure.class, "getString", ContentResolver.class, String.class, new XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                if ("default_input_method".equals(param.args[1])) {
                    param.setResult("com.sohu.inputmethod.sogou");
                }
            }
        });
    }


    private static void generateAndSend(final EditText editText) {// this editText object is Instance of XEditTextEx
        Log.d(TAG, "generateAndSend method invkoed!!!!");

         editText.post(new Runnable() {
            @Override
            public void run() {
                //声明 一个 转图工具类
                String path = ToImage.convertTextToImageAndSave(editText.getContext(),editText.getText().toString());

                if (onPrivateIMECommandMethod != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("SOGOU_EXP_PATH", path);
                    try {
                        onPrivateIMECommandMethod.invoke(editText, "com.sogou.inputmethod.expression", bundle);

                        Log.e(TAG, "send picture 成功:" + editText.getText().toString());

                    } catch (Throwable e) {
                        Log.e(TAG, "send picture failed", e);
                    }
                }


                if (isCleanEdit) {
                    editText.setText("");
                }
            }
        });

    }

}
